// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use calamine::{open_workbook_auto_from_rs, Reader};
use file_header::handler as file_header_parse;
use handle_variable::handler::to_snake_case;
use std::{ io::Cursor};

mod parse_result;
use parse_result::ParseResult;

// Learn more about Tauri commands at https://v1.tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name_name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name_name)
}

#[tauri::command]
fn en_to_variable(source_value: &str) -> String {
    to_snake_case(source_value)
}

#[tauri::command]
fn handle_file(file_data: Vec<u8>, header_row: usize) -> Result<ParseResult, String> {
    // 1. 将字节数据转换为内存流
    let cursor = Cursor::new(file_data);
    let mut headers = Vec::new();

    // 2. 直接从内存流打开Excel
    let mut workbook =
        open_workbook_auto_from_rs(cursor).map_err(|e| format!("Excel解析失败: {}", e))?;

    let sheet_names = workbook.sheet_names();
    if let Some(sheet_name) = sheet_names.first() {
        let sheet = workbook
            .worksheet_range(sheet_name)
            .map_err(|e| format!("获取Sheet失败: {}", e))?;
        // let header_data = sheet.rows().nth(header_row - 1).unwrap();
        // if let Some(header_data) = sheet.rows().nth(header_row - 1){
        //     headers = header_data.iter().map(|cell| cell.to_string()).collect();
        // }else{
        //     return Err(format!("Sheet中未找到第{}行数据", header_row));
        // }
        headers = match sheet.rows().nth(header_row - 1) {
            Some(header_data) => {
                // headers = ;
                Ok(header_data.iter().map(|cell| cell.to_string()).collect())
            }
            None => Err(format!("Sheet中未找到第{}行数据", header_row)),
        }?;
        // headers = aa?;

        // headers = header_data.iter().map(|cell| cell.to_string()).collect();
        // for header in header_data {
        //     headers.push(header.to_string());
        // }
    }
    let new_headers = file_header_parse::header_to_variable(&headers);
    let models = file_header_parse::header_to_model(&headers);
    let sqls = file_header_parse::header_to_sql(&headers, "table_name");
    Ok(ParseResult::new(headers, new_headers, models, sqls))
    // let mut result = HashMap::new();
    // result.insert("headers".to_string(), headers.join("\n"));
    // result.insert("new_headers".to_string(), new_headers.join("\n"));
    // result.insert("models".to_string(), models.join("\n"));
    // result.insert("sqls".to_string(), sqls.join("\n"));
    // println!("{:?}", result);
    // Ok(result)
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet, en_to_variable, handle_file])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
